package com.unisci.android;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.github.StaggeredGridView;
import com.github.StaggeredGridView.OnItemClickListener;
import com.unisci.android.adapter.ProjectItemAdapter;
import com.unisci.android.dialog.CreateProjectDialog;
import com.unisci.android.dialog.CreateProjectDialog.onCreateProjectListener;
import com.unisci.android.utils.ProjectItem;
import com.unisci.android.utils.ToastShow;
import com.unisci.android.wifi.WifiAdmin;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener,
		onCreateProjectListener, OnItemClickListener {
	public static final String TAG = "PCR";
	private final String SSID_TITLE = "UniSci";
	private String mSsid;
	private final String PASSWORD = "unisci110";
	private final int WIFI_TYPE = 3;
	private final int CONNECT_TIMEOUT = 2000;
	private WifiAdmin mWifiAdmin;
	// private List<String> mSsidList;
	private Handler mConnectWifiHandler;
	private boolean isConnected = false;
	private boolean isFound = false;
	private int retryIndex = 0;
	private static final int RETRY_MAX = 10;
	private ProgressDialog mProgressDialog;

	private StaggeredGridView mGridView;
	private ProjectItemAdapter mAdapter;
	private List<HashMap<String, String>> mData;

	private ToastShow mToast;

	private ImageView mAddImageView;
	private CreateProjectDialog mCreateProjectDialog;

	private ImageView mWifiStatusImageView;
	private TextView mWifiStatusTextView;

	// private int mProjectIndex = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		init_ui();
		connectToPCR();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	private void init_ui() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setCancelable(false);
		mProgressDialog.setMessage("Connecting to PCR device...");
		// mProgressDialog.show();
		mToast = new ToastShow(this);

		mAddImageView = (ImageView) findViewById(R.id.iv_add);
		mAddImageView.setOnClickListener(this);

		mWifiStatusImageView = (ImageView) findViewById(R.id.iv_wifi_status);
		mWifiStatusTextView = (TextView) findViewById(R.id.tv_wifi);

		// init for grid view
		mData = new ArrayList<HashMap<String, String>>();
		mAdapter = new ProjectItemAdapter(this, mData, R.layout.item_project,
				new String[] { "image", "name", "time" }, new int[] {
						R.id.item_image, R.id.item_name, R.id.item_time });
		mGridView = (StaggeredGridView) findViewById(R.id.grid_view);
		mGridView.setOnItemClickListener(this);
		mGridView.setAdapter(mAdapter);
		mCreateProjectDialog = new CreateProjectDialog(this);
		mCreateProjectDialog.setOnCreateProjectListener(this);
		// load db
		List<String> tables = UnisciApplication.getInstance().getDb()
				.getTables();

		if (tables.size() > 0) {

			List<ProjectItem> items = UnisciApplication.getInstance().getDb()
					.getRecords("zhangjie");

			for (int i = 0; i < items.size(); i++) {
				addItem(items.get(i).getName(), items.get(i).getT());
			}
		} else {
			mToast.toastShow("No record");
		}
	}

	private void addItem(String name, String time) {
		HashMap<String, String> item = new HashMap<String, String>();
		item.put("name", name);
		item.put("time", time);
		mData.add(0, item);
		mAdapter.notifyDataSetChanged();
	}

	Runnable connectRunnable = new Runnable() {

		@Override
		public void run() {
			retryIndex += 1;
			if (retryIndex > RETRY_MAX) {
				mProgressDialog.dismiss();
				mToast.toastShow("Connect Timeout!");
				return;
			}
			if (!isFound) {
				List<ScanResult> results = mWifiAdmin.getWifiList();
				Log.d(TAG, "RUNNING...");
				for (int i = 0; i < results.size(); i++) {
					String ssid = results.get(i).SSID;
					Log.d(TAG, "SSID = " + ssid);
					if (ssid.startsWith(SSID_TITLE)) {
						isFound = true;
						mSsid = ssid;
						break;
					}
				}
			}

			if (!isFound) {
				mWifiAdmin.startScan();
				mConnectWifiHandler.postDelayed(this, CONNECT_TIMEOUT);
			} else {
				Log.d(TAG, "FOUND!!");
				mProgressDialog.setMessage("Find PCR device, try to connect.");
				// connect to wifi
				if (!isConnected) {
					Log.d(TAG, "CONNECT!!");
					mWifiAdmin.addNetwork(mWifiAdmin.CreateWifiInfo(mSsid,
							PASSWORD, WIFI_TYPE));
					mWifiAdmin.connect();
					mConnectWifiHandler.postDelayed(this, CONNECT_TIMEOUT);
					Log.d(TAG, "getssid = " + mWifiAdmin.getSSID()
							+ ", mssid = " + mSsid);
					if (mWifiAdmin.getSSID().contains(mSsid)) {
						isConnected = true;
						setConnected();
					}
				} else {
					mProgressDialog.dismiss();
				}
			}

		}
	};

	private void setConnected() {
		mWifiStatusImageView.setImageResource(R.drawable.ic_wifi_signal_level3);
		mWifiStatusTextView.setText("已连接");
	}

	private void connectToPCR() {
		isFound = false;
		isConnected = false;
		retryIndex = 0;
		mConnectWifiHandler = new Handler();
		// mSsidList = new ArrayList<String>();
		mWifiAdmin = new WifiAdmin(this);
		mWifiAdmin.openWifi();
		mWifiAdmin.startScan();
		mConnectWifiHandler.post(connectRunnable);
		mProgressDialog.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.iv_add) {
			mCreateProjectDialog.show();
		}
	}

	private void saveDefaultProject(String name, String time) {
		ProjectItem item = new ProjectItem();
		item.setIndex(-1);
		item.setName(name);
		item.setT(time);
		item.setTemp(0, 95f);
		item.setTemp(1, 90f);
		item.setTemp(2, 55f);
		item.setTemp(3, 74f);
		item.setTemp(4, 4f);
		item.setTime(0, 12);
		item.setTime(1, 10);
		item.setTime(2, 10);
		item.setTime(3, 20);
		item.setTime(4, 1440);
		item.setTempDown(2, -1);
		item.setLoopStage(3, 1);
		item.setLoop(3, 30);
		UnisciApplication.getInstance().getDb().saveRecord("zhangjie", item);
	}

	@Override
	public void onCreateProject(String name) {
		// TODO Auto-generated method stub
		if (name.length() < 1) {
			mToast.toastShow("名称不能为空!");
		} else {
			// setup time
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH");
			String time = format.format(new Date());
			addItem(name, time);
			// save project
			saveDefaultProject(name, time);
			mCreateProjectDialog.dismiss();
		}
	}

	@Override
	public void onItemClick(StaggeredGridView parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		mToast.toastShow("click " + position);
		Intent intent = new Intent();
		intent.putExtra("name", mData.get(position).get("name"));
		intent.setClass(MainActivity.this, WorkActivity.class);
		startActivity(intent);
	}

}